package drds.data_propagate.driver.utils;

import drds.data_propagate.driver.packets.HeaderPacket;
import drds.data_propagate.driver.socket.SocketChannel;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public abstract class PacketManager {

    public static HeaderPacket readHeader(SocketChannel socketChannel, int length) throws IOException {
        HeaderPacket headerPacket = new HeaderPacket();
        headerPacket.decode(socketChannel.read(length));
        return headerPacket;
    }

    public static HeaderPacket readHeader(SocketChannel socketChannel, int length, int timeout) throws IOException {
        HeaderPacket headerPacket = new HeaderPacket();
        headerPacket.decode(socketChannel.read(length, timeout));
        return headerPacket;
    }

    //
    public static byte[] readBytes(SocketChannel socketChannel, int length) throws IOException {
        return socketChannel.read(length);
    }

    public static byte[] readBytes(SocketChannel socketChannel, int length, int timeout) throws IOException {
        return socketChannel.read(length, timeout);
    }

    //
    public static void writePackets(SocketChannel socketChannel, byte[]... bytess) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        for (byte[] bytes : bytess) {
            byteArrayOutputStream.write(bytes);
        }
        socketChannel.write(byteArrayOutputStream.toByteArray());
    }

    public static void writeBodyBytes(SocketChannel socketChannel, byte[] bodyBytes) throws IOException {
        writeBodyBytes(socketChannel, bodyBytes, (byte) 0);
    }

    public static void writeBodyBytes(SocketChannel socketChannel, byte[] bodyBytes, byte packetSeqNumber)
            throws IOException {
        HeaderPacket headerPacket = new HeaderPacket();
        headerPacket.setPacketBodyLength(bodyBytes.length);
        headerPacket.setPacketSequenceNumber(packetSeqNumber);
        socketChannel.write(headerPacket.encode(), bodyBytes);
    }
}
